import {MyNavBar, ShowLoading} from '@/components'

import './index.less'
import {useListHook} from '@/hooks'
import {_getCollection, _delCollection, _postCollection} from './store'
import CollectionItem from './components/collectionItem'
import {useEffect, useState} from 'react'
import {Toast} from 'antd-mobile'

function Collection() {
  const {data, showLoading} = useListHook({func: _getCollection})

  const [ tempData, setTempData ] = useState(null)

  const [ isFirst, setIsFirst ] = useState(true)

  useEffect(() => {
    if (isFirst) {
      setTempData(data.map(item => ({...item, isCollect: true})))
      setIsFirst(false)
    } else {
      const temp = []
      for (let i = 0, len = data.length; i < len; i++) {
        if (tempData[i] && !tempData[i].isCollect) {
          temp.push(tempData[i])
        } else {
          temp.push({...data[i], isCollect: true})
        }
      }
      setTempData(temp)
    }
  }, [ data ])

  const handleClick = async (data, isCollect, index) => {
    let result = null
    if (isCollect) {
      result = await _delCollection(data)
    } else {
      result = await _postCollection(data)
    }
    if (result) {
      Toast.success('操作成功')
      const temp = JSON.parse(JSON.stringify(tempData))
      temp[index].isCollect = !temp[index].isCollect
      setTempData(temp)
    }
  }

  return (
    <div>
      <MyNavBar title='我的收藏'/>
      <div className='collection'>
        {data?.length ? tempData.map((item, index) => (
          <CollectionItem handleClick={handleClick} data={item} key={item.id} index={index}/>
        )) : ''}
        <ShowLoading showLoading={showLoading}/>
      </div>
    </div>
  )
}

export default Collection
